const WebSocket = require("ws");
const wss = new WebSocket.Server({ port: 8084 });
// 用于存储用户名与WebSocket连接的映射
const roomMap = new Map();
let roomListG = [];

wss.on("connection", function connection(ws) {
  ws.on("message", function incoming(data) {
    if (data instanceof Buffer) {
      // 如果接收到的是 Buffer 对象，将其转换为字符串
      data = data.toString("utf8");
    }

    let objMsg = JSON.parse(data);
    //房间处理
    const roomId = objMsg.roomInfo.roomId;

    //给连接上绑定自定义属性
    ws.fleetRoomId = roomId;
    ws.fleetMessageBean = objMsg;

    // console.log("Received message: ", roomId, data);
    if (!roomMap.has(roomId)) {
      roomMap.set(roomId, new Set());
    }

    if (!roomMap.get(roomId).has(ws)) {
      roomMap.get(roomId).add(ws);
    }

    //新用户加入的话,更新房间信息
    if (objMsg.message.roomUpdate) {
      console.log("Received message: ", roomId, data);
      getRoomListInfoUpdate();
    }

    objMsg.roomInfo.count = roomMap.get(roomId).size;
    if (objMsg.message.type === "heartbeat") {
      getRoomListInfoUpdate();
      objMsg.roomList = getRoomListInfo();
      ws.send(JSON.stringify(objMsg));
    } else {
      // Broadcast message to all clients
      const roomClients = roomMap.get(roomId);
      if (roomClients) {
        roomClients.forEach(function (client) {
          if (objMsg.message.roomUpdate) {
            if (client.readyState === WebSocket.OPEN) {
              objMsg.roomInfo.count = roomClients.size;
              objMsg.roomList = getRoomListInfo();
              client.send(JSON.stringify(objMsg));
            }
          } else {
            if (client !== ws && client.readyState === WebSocket.OPEN) {
              objMsg.roomInfo.count = roomClients.size;
              client.send(JSON.stringify(objMsg));
            }
          }
        });
      }
    }
  });

  ws.on("close", function close() {
    // 从所有房间中删除断开连接的客户端
    roomMap.forEach(function (client, roomId) {
      if (client.has(ws)) {
        client.delete(ws);
        console.log(
          ws.fleetMessageBean.userInfo.name + ": 离开了===>",
          ws.fleetRoomId,
          roomMap.size
        );
      }
      if (client.size === 0) {
        console.log(`房间${roomId}没人了, 删除房间`);
        roomMap.delete(roomId);
        console.log(`删除后的房间数: ${roomMap.size}`);
      }
    });

    //离开房间通知
    const roomClients = roomMap.get(ws.fleetRoomId);
    if (roomClients) {
      //房间列表更新
      getRoomListInfoUpdate();
      ws.fleetMessageBean.roomList = getRoomListInfo();
      ws.fleetMessageBean.roomListUpdate = true;
      //房间列表更新]]

      //通知
      roomClients.forEach(function (client) {
        if (client !== ws && client.readyState === WebSocket.OPEN) {
          ws.fleetMessageBean.message.type = "msg";
          ws.fleetMessageBean.message.content = `${ws.fleetMessageBean.userInfo.name}离开了房间`;
          ws.fleetMessageBean.roomInfo.count = roomClients.size;
          client.send(JSON.stringify(ws.fleetMessageBean));
        }
      });
    }
  });
});

function getRoomListInfo() {
  return roomListG;
}
function getRoomListInfoUpdate() {
  roomListG = [];
  roomMap.forEach((v, k) => {
    roomListG.push({
      roomId: k,
      count: v.size,
    });
  });
  return roomListG;
}
